package com.cskaoyan.shopping.service.impl;


import com.cskaoyan.shopping.constants.ShoppingRetCode;
import com.cskaoyan.shopping.converter.CartsConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.exception.ExceptionProcessorUtils;
import com.cskaoyan.shopping.form.CheckAllItemRequest;
import com.cskaoyan.shopping.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Slf4j
@Service
public class ICartServiceImpl implements ICartService {

    private final String CART = "cart";

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    CartsConverter cartConverter;


    // TODO: 2022/10/26  获得购物车

    /**
     * solution:
     */
    @Override
    public List<CartsProductDto> getCartListById(Long userId) {

        List<CartsProductDto> cartsProductDtos = new ArrayList<>();
        //通过userId访问redis数据库查询到商品id
        //1.拿到对应用户的购物车中商品的信息
        RMap<Object, Object> map = redissonClient.getMap(userId + CART);

        Collection<Object> values = map.values();

        for (Object value : values) {
            cartsProductDtos.add((CartsProductDto) value);
        }
        Collections.sort(cartsProductDtos, new Comparator<CartsProductDto>() {
            @Override
            public int compare(CartsProductDto o1, CartsProductDto o2) {
                return o2.getUpdateTime().compareTo(o1.getUpdateTime());
            }
        });

        return cartsProductDtos;
    }

    // TODO: 2022/10/26  选择购物车

    /**
     * 全选
     */
    @Override
    public void checkAllCartItem(CheckAllItemRequest request) {
        //拿到map
        RMap<Object, CartsProductDto> map = redissonClient.getMap(request.getUserId() + CART);


        //Set<Object> keySet = map.keySet();


//            //全选
//            for (Object o : keySet) {
//                CartsProductDto cartsProductDto = map.get(o);
//                cartsProductDto.setChecked("true");
//                map.put(o, cartsProductDto);
//            }
        map.forEach((k, v) -> {
            v.setChecked(request.getChecked());
            map.put(k, v);
        });

    }


    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();

        try {
            request.requestCheck();
            RMap<Object, Object> rMap = redissonClient.getMap(request.getUserId() + CART);
            //先判断该商品在不在购物车
            if (rMap.containsKey(request.getItemId())) {
                CartsProductDto cartVo = (CartsProductDto) rMap.get(request.getItemId());
                cartVo.setProductNum(cartVo.getProductNum() + request.getNum());
                cartVo.setUpdateTime(new Date());
                rMap.put(request.getItemId(), cartVo);
            } else {
                //查数据库
                Item item = itemMapper.selectByPrimaryKey(request.getItemId());
                CartsProductDto cartVo = cartConverter.item2CartVo(item);
                cartVo.setChecked("true");
                cartVo.setProductNum(request.getNum());
                cartVo.setLimitNum((long) item.getLimit_num());
                String[] split = item.getImage().split(",");
                cartVo.setProductImg(split[0]);
                cartVo.setUpdateTime(new Date());
                rMap.put(cartVo.getProductId(), cartVo);
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("IcartServiceImpl.addToCart occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            request.requestCheck();
            RMap<Object, CartsProductDto> map = redissonClient.getMap(request.getUserId() + CART);
            CartsProductDto cartsProductDto = map.get(request.getItemId());
            cartsProductDto.setProductNum(request.getNum());
            cartsProductDto.setChecked(request.getChecked());
            map.put(request.getItemId(), cartsProductDto);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.updateCartNum occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            request.requestCheck();
            RMap<Object, CartsProductDto> map = redissonClient.getMap(request.getUserId() + CART);
            map.remove(request.getItemId());
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("IcartServiceImpl.addToCart occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public DeleteCheckedItemResponse deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResponse response = new DeleteCheckedItemResponse();
        try {
            request.requestCheck();
            RMap<Object, CartsProductDto> map = redissonClient.getMap(request.getUserId() + CART);
            map.forEach((k, v) -> {
                if (Boolean.parseBoolean(v.getChecked())) {
                    map.remove(k);
                }
            });
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("IcartServiceImpl.addToCart occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }


}
